Page({
  data: {
    ingredientList: [],
  },

  onLoad() {
    const list = wx.getStorageSync('ingredientList') || [];
    this.setData({ ingredientList: list }, () => {
      this.calculateCompleted();
    });
  },

  // 切换折叠/展开状态
  toggleCollapse(e) {
    const index = e.currentTarget.dataset.index; // 获取点击的菜单索引
    const ingredientList = [...this.data.ingredientList];
    const group = ingredientList[index];

    // 切换 isCollapsed 状态
    group.isCollapsed = !group.isCollapsed;
    this.setData({
      ingredientList
    });
  },

  // 勾选食材的完成状态
  toggleComplete(e) {
    const { name, title } = e.currentTarget.dataset;

    const updatedList = this.data.ingredientList.map(recipe => {
      if (recipe.title === title) {
        return {
          ...recipe,
          ingredients: recipe.ingredients.map(item =>
            item.name === name ? { ...item, completed: !item.completed } : item
          )
        };
      }
      return recipe;
    });

    this.setData({
      ingredientList: updatedList
    }, () => {
      wx.setStorageSync('ingredientList', updatedList);
      this.calculateCompleted();
    });
  },

  // 删除菜单
  deleteRecipe(e) {
    const title = e.currentTarget.dataset.title;

    wx.showModal({
      title: '确认删除',
      content: `确定要删除这个清单吗？`,
      showCancel: true, // 显示取消按钮
      cancelText: '取消',
      cancelColor: '#666',
      confirmText: '确认',
      confirmColor: '#f44336', // 确认按钮为红色
      success: (res) => {
        if (res.confirm) {
          // 删除菜单
          const updatedList = this.data.ingredientList.filter(item => item.title !== title);
          this.setData({
            ingredientList: updatedList
          });

          // 更新本地存储
          wx.setStorageSync('ingredientList', updatedList);
        }
      }
    });
  },

  calculateCompleted() {
    const completed = this.data.ingredientList.flatMap(recipe =>
      recipe.ingredients
        .filter(item => item.completed)
        .map(item => ({
          ...item,
          originTitle: recipe.title
        }))
    );

    this.setData({
      completedList: completed
    });
  }
});
